package com.mtw.bbs.article.controller.user;



import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mtw.bbs.constant.TopicConstant;
import com.mtw.bbs.article.pojo.entity.TopicMember;
import com.mtw.bbs.article.pojo.form.TopicForm;
import com.mtw.bbs.article.pojo.form.TopicMemberForm;
import com.mtw.bbs.article.pojo.vo.UserTopicVo;
import com.mtw.bbs.article.service.TopicMemberService;
import com.mtw.bbs.article.service.TopicIndexService;
import com.mtw.bbs.common.core.constant.SysConstant;
import com.mtw.bbs.common.core.enums.ResultCode;
import com.mtw.bbs.common.core.security.UserDetails;
import com.mtw.bbs.common.core.security.context.SecurityContextHolder;
import com.mtw.bbs.common.core.vo.Result;
import com.mtw.bbs.userAdmin.feign.UserClient;
import com.mtw.bbs.userAdmin.pojo.dto.UserDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.util.List;


/**
 * 话题接口层
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("user/topic")
public class UserTopicController {

    private final UserClient userClient;
    private final TopicIndexService topicIndexService;
    private final TopicMemberService topicMemberService;






    /**
     * 获取用户已加入的话题
     *
     * @param page 当前页
     * @param size 分页大小
     */
    @GetMapping("/joinedList")
    public Result getUserJoinedTopic(@RequestParam(name = "page") int page,
                                     @RequestParam(name = "size") int size) {

        UserDetails details = SecurityContextHolder.getContext().getAuthentication();
        if (details == null) {
            return Result.fail(ResultCode.NO_AUTH);
        }
        Page<UserTopicVo> voPage = topicIndexService.getUserJoinTopicVoPage(page, size, false, details.getId());
        return Result.success(voPage);
    }


    /**
     * 获取用户已加入的话题
     *
     */
    @GetMapping("/memberType/{topicId}")
    public Result getMemberType(@PathVariable("topicId") String topicId) {

        UserDetails details = SecurityContextHolder.getContext().getAuthentication();
        if (details == null) {
            return Result.fail(ResultCode.NO_AUTH);
        }
        return Result.success(topicMemberService.userJoinedTopic(details.getId(),topicId));
    }



    /**
     * 获取用户管理的话题
     *
     * @param page 当前页
     * @param size 分页大小
     */
    @GetMapping("/adminList")
    public Result getUserAdminTopic(@RequestParam(name = "page") int page,
                                    @RequestParam(name = "size") int size) {

        UserDetails details = SecurityContextHolder.getContext().getAuthentication();
        if (details == null) {
            return Result.fail(ResultCode.NO_AUTH);
        }
        Page<UserTopicVo> voPage = topicIndexService.getUserJoinTopicVoPage(page, size, true, details.getId());
        return Result.success(voPage);
    }





    /**
     * 新增话题
     * @param form 表单信息
     */
    @PostMapping("/save")
    public Result saveTopic(@RequestBody TopicForm form) {

        UserDetails details = SecurityContextHolder.getContext().getAuthentication();
        if (details == null) {
            return Result.fail(ResultCode.NO_AUTH);
        }
        form.setStatus(SysConstant.DEFAULT_ENABLE);
        form.setTypeId("0");
        boolean saved = topicIndexService.saveTopic(form);
        return saved ? Result.success() : Result.fail("保存失败");
    }




    /**
     * 修改话题信息
     *
     * @param form 表单信息
     */
    @PutMapping("/update")
    public Result updateTopic(@RequestBody TopicForm form) {

        UserDetails details = SecurityContextHolder.getContext().getAuthentication();
        if (details == null) {
            return Result.fail(ResultCode.NO_AUTH);
        }
        LambdaQueryWrapper<TopicMember> mqw = new LambdaQueryWrapper<>();
        mqw.eq(TopicMember::getTopicId, form.getId());
        mqw.eq(TopicMember::getUserId, details.getId());
        mqw.and(nlq->nlq.eq(TopicMember::getMemberType, TopicConstant.TOPIC_MASTER)
                        .or()
                        .eq(TopicMember::getMemberType, TopicConstant.TOPIC_ADMIN));

        TopicMember member = topicMemberService.getOne(mqw);
        if (member == null) {
            return Result.fail("无修改权限");
        }
        boolean updated = topicIndexService.updateTopic(form);
        return updated ? Result.success() : Result.fail("保存失败");
    }



    /**
     * 加入话题
     *
     */
    @PostMapping("/op/{id}")
    public Result joinTopic(@PathVariable("id") String id) {

        UserDetails details = SecurityContextHolder.getContext().getAuthentication();
        if (details == null) {
            return Result.fail(ResultCode.NO_AUTH);
        }
        boolean result = topicMemberService.joinTopic(details.getId(), id, TopicConstant.TOPIC_USER);
        return result?Result.success():Result.fail("加入话题失败");
    }



    /**
     * 退出话题
     *
     */
    @DeleteMapping("/op/{id}")
    public Result withdrawalTopic(@PathVariable("id") String id) {

        UserDetails details = SecurityContextHolder.getContext().getAuthentication();
        if (details == null) {
            return Result.fail(ResultCode.NO_AUTH);
        }
        LambdaQueryWrapper<TopicMember> lqw = new LambdaQueryWrapper<>();
        lqw.eq(TopicMember::getUserId, details.getId());
        lqw.eq(TopicMember::getTopicId, id);
        List<TopicMember> list = topicMemberService.list(lqw);
        if (CollectionUtil.isEmpty(list)){
            return Result.success();
        }
        if (TopicConstant.TOPIC_MASTER.equals(list.get(0).getMemberType())){
            return Result.fail("请变更题主后再退出！");
        }
        topicMemberService.deleteMember(list.get(0));
        return Result.success();
    }




    /**
     * 某用户设置为话题管理员
     *
     * @param form 表单信息
     */
    @PutMapping("/admin")
    public Result becomeAdmin(@RequestBody TopicMemberForm form) {

        UserDetails details = SecurityContextHolder.getContext().getAuthentication();
        if (details == null) {
            return Result.fail(ResultCode.NO_AUTH);
        }
        LambdaQueryWrapper<TopicMember> mqw = new LambdaQueryWrapper<>();
        mqw.eq(TopicMember::getTopicId,form.getTopicId());
        mqw.eq(TopicMember::getUserId,details.getId());
        mqw.eq(TopicMember::getMemberType, TopicConstant.TOPIC_MASTER);
        long count = topicMemberService.count(mqw);
        if (count <1){
            return Result.fail("无修改权限");
        }

        Result<UserDto> userinfo = userClient.getUserInfoByUsername(form.getUsername());
        if (userinfo.isSuccess() && userinfo.getData() != null){
            boolean updated = topicMemberService.updateMemberType(userinfo.getData().getId(),form.getTopicId(),TopicConstant.TOPIC_ADMIN);
            return updated?Result.success():Result.fail("保存失败");
        }

        return Result.fail("保存失败");
    }




    /**
     * 取消某用户的话题管理员身份
     *
     * @param form 表单信息
     */
    @DeleteMapping("/admin")
    public Result cancelAdmin(@RequestBody TopicMemberForm form) {

        UserDetails details = SecurityContextHolder.getContext().getAuthentication();
        if (details == null) {
            return Result.fail(ResultCode.NO_AUTH);
        }
        LambdaQueryWrapper<TopicMember> mqw = new LambdaQueryWrapper<>();
        mqw.eq(TopicMember::getTopicId,form.getTopicId());
        mqw.eq(TopicMember::getUserId,details.getId());
        mqw.eq(TopicMember::getMemberType, TopicConstant.TOPIC_MASTER);
        long count = topicMemberService.count(mqw);
        if (count <1){
            return Result.fail("无修改权限");
        }

        Result<UserDto> userinfo = userClient.getUserInfoByUsername(form.getUsername());
        if (userinfo.isSuccess() && userinfo.getData() != null){
            boolean updated = topicMemberService.updateMemberType(userinfo.getData().getId(),form.getTopicId(),TopicConstant.TOPIC_USER);
            return updated?Result.success():Result.fail("保存失败");
        }

        return Result.fail("保存失败");
    }


}
